package com.jhd.jiangxi.activity.scan.in.purchase;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;
import com.google.android.material.tabs.TabLayout;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.main.BaseActivity;
import com.jhd.jiangxi.activity.scan.in.returns.ReturnInActivity;
import com.jhd.jiangxi.activity.scan.in.supply.SupplyActivity;
import com.jhd.jiangxi.entity.LastInputEditText;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.util.DeptChoose;
import com.jhd.jiangxi.util.EditTextDel;
import com.jhd.jiangxi.util.PopWindow;
import com.jhd.jiangxi.util.ScanUtil;
import com.jhd.jiangxi.vo.Approval;
import com.jhd.jiangxi.vo.GlobalDictionary;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.PiatsInfo;
import com.jhd.jiangxi.vo.PriceBook;
import com.jhd.jiangxi.vo.RefDept;

import net.zigin.commons.util.CollectionUtil;
import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.jiangxi.activity.scan.in.supply.SupplyStorageActivity.electCodePackageVos;

/*采购入库*/
public class PurchaseActivity extends BaseActivity implements View.OnClickListener, PurchaseBillFragment.OnFragmentInteractionListener, PurchaseContentFragment.OnFragmentInteractionListener {

    private PurchaseBillFragment purchaseBillFragment;
    private PurchaseContentFragment purchaseContentFragment;
    private ViewPager vp;
    private List<Fragment> mDatas = new ArrayList<Fragment>();
    private TabLayout tabs;
    private FragmentPagerAdapter adapter;
    private RecyclerView rvStorage;
    private Button btnSubmitVaccine, btnDelAllVaccine;
    private LastInputEditText btnSupplyDept,btnDeliveryDept;
    private TextView  btnVaccineType, btnPriceBook, btnStartTime, btnEndTime, btnTransportEquip, btnApprovalIn;
    private List<String> name = new ArrayList<>();
    private List<String> id = new ArrayList<>();
    private List<String> deptCode = new ArrayList<>();
    private List<String> deptId = new ArrayList<>();
    private List<String> deptInstitutionalType = new ArrayList<>();
    private String produceMappingId;
    private boolean isDeptCode=false;
    private String[] categoryName = {"国家免疫规划疫苗", "地方免疫规划疫苗", "应急接种疫苗", "非免疫规划疫苗", "群体性预防接种疫苗", "紧急使用疫苗"};
    private String[] categoryId = {"1", "4", "5", "2", "6", "7"};
    private List<GlobalDictionary> globalDictionaryList;
    public static List<PiatsInfo> piatsInfoList = new ArrayList<>();
    public List<PiatsInfo> piatsInfoList2 = new ArrayList<>();//对应储位的已扫(包括已扫和之前进入该页面扫过的)
    public List<PiatsInfo> piatsInfoList3 = new ArrayList<>();//本次扫描的
    private RecyclerAdapter recyclerAdapter;
    private MyBroadcastReceiver broadcast;
    private BarcodeDataReceiver barcodeDataReceiver;
    private Button btnToTemp;
    private Context context = PurchaseActivity.this;
    private ListView listView;
    private PopupWindow popup;
    private AlertDialog _alertDialog=null;
    private boolean isCheck=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase);
        listView = new ListView(context);
        popup= new PopupWindow(context);;
        getBack(PurchaseActivity.this);
        openScan(context);
        getGlobalDictionaryByType();
        initView();
        initEvent();
    }

    private void initView() {
        initHeader("采购入库");
        vp = (ViewPager) findViewById(R.id.vpSheet);
        purchaseBillFragment = new PurchaseBillFragment();
        purchaseContentFragment = new PurchaseContentFragment();
        mDatas.add(purchaseBillFragment);
        mDatas.add(purchaseContentFragment);
        tabs = findViewById(R.id.tabSheet);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (vp.getCurrentItem() == 0) {
                onBackPressed();
            } else if (vp.getCurrentItem() == 1) {
                for (PiatsInfo piatsInfo : piatsInfoList3) {
                    if (piatsInfoList.contains(piatsInfo)) {
                        piatsInfoList.remove(piatsInfo);
                    }
                }
                Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
                sendBroadcast(stopIntent);
                startActivity(new Intent(PurchaseActivity.this, PurchaseStorageActivity.class));
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initEvent() {
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                添加选中Tab的逻辑
                if (tab.getPosition() == 1) {
                    btnToTemp();
                } else if (tab.getPosition() == 0) {
                    ScanUtil.powerOffScan(context);
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                添加未选中Tab的逻辑
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
//                再次选中tab的逻辑
            }
        });
        tabs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        adapter = new FragmentPagerAdapter(getSupportFragmentManager(), 1) {
            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mDatas.get(position);
            }
        };
        vp.setAdapter(adapter);
        tabs.setupWithViewPager(vp);
        TabLayout.Tab tab = tabs.getTabAt(0);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_left);
        tab.setText("交货单");
        tab = tabs.getTabAt(1);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_right);
        tab.setText("扫码入库");
    }

    /*IssueBillFragment的寻址*/
    @SuppressLint("WrongViewCast")
    @Override
    public void fragmentCreated(View view) {
        super.fragmentCreated(view);
        btnSupplyDept = (LastInputEditText) view.findViewById(R.id.btnSupplyDept);
        btnVaccineType = (TextView) view.findViewById(R.id.btnVaccineType);
        btnPriceBook = (TextView) view.findViewById(R.id.btnPriceBook);
        btnStartTime = (TextView) view.findViewById(R.id.btnStartTime);
        btnEndTime = (TextView) view.findViewById(R.id.btnEndTime);
        btnApprovalIn = (TextView) view.findViewById(R.id.btnApprovalIn);
        btnTransportEquip = (TextView) view.findViewById(R.id.btnTransportEquip);
        btnDeliveryDept = (LastInputEditText) view.findViewById(R.id.btnDeliveryDept);
        btnToTemp=(Button)view.findViewById(R.id.btnToTemp);
        btnToTemp.setOnClickListener(PurchaseActivity.this);
        //btnSupplyDept.setOnClickListener(PurchaseActivity.this);
        btnVaccineType.setOnClickListener(PurchaseActivity.this);
        btnPriceBook.setOnClickListener(PurchaseActivity.this);
        btnStartTime.setOnClickListener(PurchaseActivity.this);
        btnEndTime.setOnClickListener(PurchaseActivity.this);
        btnTransportEquip.setOnClickListener(PurchaseActivity.this);
//        btnDeliveryDept.setOnClickListener(PurchaseActivity.this);
        btnApprovalIn.setOnClickListener(PurchaseActivity.this);
        getDept();getVaccineDistributionDempartByDeptId();
        getApproval(btnApprovalIn,"采购入库");
        getPriceBookMst();//获取价格本列表
        //默认到达时间是当前时间
        btnEndTime.setText(getTime(new Date()));
        btnEndTime.setTextColor(getResources().getColor(R.color.billTextChoose));
        application.setArrivalTime(btnEndTime.getText().toString());
        btnSupplyDept.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name.clear();id.clear();deptId.clear();deptCode.clear();deptInstitutionalType.clear();
                if (deptList != null&&isCheck==false) {
                    for (RefDept refDept : deptList) {
                        if(refDept.getName().contains(btnSupplyDept.getText().toString())&&"1".equals(refDept.getInstitutionalType())){
                            name.add(refDept.getName());
                            id.add(refDept.getId());
                            deptId.add(refDept.getRefDeptId());
                            deptCode.add(refDept.getDeptCode());
                            deptInstitutionalType.add(refDept.getInstitutionalType());
                        }
                    }
                    show(btnSupplyDept, name, id);
                }
            }
        });
        btnSupplyDept.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    name.clear();id.clear();deptId.clear();deptCode.clear();deptInstitutionalType.clear();
                    if (deptList != null) {
                        for (RefDept refDept : deptList) {
                            if(refDept.getName().contains(btnSupplyDept.getText().toString())&&"1".equals(refDept.getInstitutionalType())){
                                name.add(refDept.getName());
                                id.add(refDept.getId());
                                deptId.add(refDept.getRefDeptId());
                                deptCode.add(refDept.getDeptCode());
                                deptInstitutionalType.add(refDept.getInstitutionalType());
                            }
                        }
                        show(btnSupplyDept, name, id);
                    }
                }
                return false;
            }
        });

        btnDeliveryDept.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name.clear();id.clear();deptId.clear();deptCode.clear();
                if (deptList != null&&isCheck==false) {
                    for (RefDept refDept : deptList2) {
                        if(refDept.getName().contains(btnDeliveryDept.getText().toString())){
                            name.add(refDept.getName());
                            id.add(refDept.getId());
                            deptId.add(refDept.getRefDeptId());
                            deptCode.add(refDept.getDeptCode());
                        }
                    }
                    show(btnDeliveryDept, name, id);
                }
            }
        });
        btnDeliveryDept.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                name.clear();id.clear();deptId.clear();deptCode.clear();
                if (deptList != null) {
                    for (RefDept refDept : deptList2) {
                        if(refDept.getName().contains(btnDeliveryDept.getText().toString())){
                            name.add(refDept.getName());
                            id.add(refDept.getId());
                            deptId.add(refDept.getRefDeptId());
                            deptCode.add(refDept.getDeptCode());
                        }
                    }
                    show(btnDeliveryDept, name, id);
                }
                return false;
            }
        });
    }

    /*IssueContentFragment的寻址*/
    @Override
    public void fragmentCreated2(View view) {
        super.fragmentCreated2(view);
        rvStorage = (RecyclerView) view.findViewById(R.id.rvStorage);
        btnSubmitVaccine = (Button) view.findViewById(R.id.btnSubmitVaccine);
        btnDelAllVaccine = (Button) view.findViewById(R.id.btnDelAllVaccine);
        LinearLayoutManager layoutManager = new LinearLayoutManager(PurchaseActivity.this);
        rvStorage.setLayoutManager(layoutManager);
        btnSubmitVaccine.setOnClickListener(PurchaseActivity.this);
        btnDelAllVaccine.setOnClickListener(PurchaseActivity.this);
    }


    private void btnToTemp(){
        if (btnApprovalIn.getText().toString().equals("审核人") || btnSupplyDept.getText().toString().equals("") || btnVaccineType.getText().toString().equals("疫苗属性") || btnPriceBook.getText().toString().equals("价格本")
                || btnStartTime.getText().toString().equals("起运时间") || btnEndTime.getText().toString().equals("到达时间")
                || btnTransportEquip.getText().toString().equals("运输设备") || btnDeliveryDept.getText().toString().equals("")) {
            UtilHelper.alertMsg(PurchaseActivity.this, "请配置好所有数据", "点击任意处关闭弹窗");
            vp.setCurrentItem(0);
        } else {
            if(!DeptChoose.isContain(deptList,btnSupplyDept.getText().toString())){
                UtilHelper.alertMsg(PurchaseActivity.this, "请选择正确的供货单位", "点击任意处关闭弹窗");
                vp.setCurrentItem(0);
            }else if(!DeptChoose.isContain(deptList,btnDeliveryDept.getText().toString())){
                UtilHelper.alertMsg(PurchaseActivity.this, "请选择正确的配送单位", "点击任意处关闭弹窗");
                vp.setCurrentItem(0);
            }else{
                if (compareDate(btnStartTime.getText().toString(), btnEndTime.getText().toString())) {
                    if(application.getVaccineType().equals(application.getCheckVaccineType())&&application.getSupplyDeptId().equals(application.getSupplyDeptId2())){//供货单位和疫苗类型没变
                        application.setCheckVaccineType(application.getVaccineType());application.setSupplyDeptId2(application.getSupplyDeptId());
                        startActivity(new Intent(PurchaseActivity.this, PurchaseStorageActivity.class));
                        vp.setCurrentItem(1);
                    }else{
                        if(piatsInfoList.size()>0){
                            vp.setCurrentItem(0);
                            isClearDialog();
                        }else{
                            application.setCheckVaccineType(application.getVaccineType());application.setSupplyDeptId2(application.getSupplyDeptId());
                            startActivity(new Intent(PurchaseActivity.this, PurchaseStorageActivity.class));
                            vp.setCurrentItem(1);
                        }
                    }
                } else {
                    UtilHelper.alertMsg(PurchaseActivity.this, "到达时间不能早于起运时间", "请重新配置时间");
                    vp.setCurrentItem(0);
                }
            }
        }
    }

    public void isClearDialog() {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setTitle("采购入库");
        alertBuilder.setMessage("供货单位或疫苗类型已经重选，将会对之前的扫描进行清空，您确定吗?");
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                application.setCheckVaccineType(application.getVaccineType());application.setSupplyDeptId2(application.getSupplyDeptId());
                piatsInfoList.clear();piatsInfoList2.clear();piatsInfoList3.clear();
                recyclerAdapter = new RecyclerAdapter(piatsInfoList2);
                rvStorage.setAdapter(recyclerAdapter);
                startActivity(new Intent(PurchaseActivity.this, PurchaseStorageActivity.class));
                vp.setCurrentItem(1);
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }

    protected void initHeader(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";
        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (vp.getCurrentItem() == 0) {
                    onBackPressed();
                } else if (vp.getCurrentItem() == 1) {
                    for (PiatsInfo piatsInfo : piatsInfoList3) {
                        if (piatsInfoList.contains(piatsInfo)) {
                            piatsInfoList.remove(piatsInfo);
                        }
                    }
                    Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
                    sendBroadcast(stopIntent);
                    startActivity(new Intent(PurchaseActivity.this, PurchaseStorageActivity.class));
                }
            }
        });
        String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
        ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnToTemp:
                vp.setCurrentItem(1);
                break;
            case R.id.btnApprovalIn://获取审批人
                name.clear();
                id.clear();
                if (approvalList != null) {
                    for (int i = 0; i < approvalList.size(); i++) {
                        name.add(approvalList.get(i).getUserName1());
                        id.add(approvalList.get(i).getId());
                    }
                    show(btnApprovalIn, name, id);
                } else {
                    Toast.makeText(context, "未获取审批人信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                }
                break;
            /*case R.id.btnSupplyDept://获取供货单位
                if(btnSupplyDept.isFocused()){
                    name.clear();
                    id.clear();
                    if (deptList != null) {
                        for (int i = 0; i < deptList.size(); i++) {
                            name.add(deptList.get(i).getName());
                            id.add(deptList.get(i).getId());
                            deptId.add(deptList.get(i).getRefDeptId());
                            deptCode.add(deptList.get(i).getDeptCode());
                        }
                        show(btnSupplyDept, name, id);
                    } else {
                        Toast.makeText(context, "未获取供货单位信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                    }
                }
                break;*/
            case R.id.btnVaccineType://获取疫苗类型
                show(btnVaccineType, Arrays.asList(categoryName),Arrays.asList(categoryId));
                break;
            case R.id.btnPriceBook://获取价格本
                name.clear();
                id.clear();
                if (priceBook != null) {
                    for (int i = 0; i < priceBook.size(); i++) {
                        name.add(priceBook.get(i).getPriceBookNo());
                        id.add(priceBook.get(i).getId());
                    }
                    show(btnPriceBook, name, id);
                } else {
                    Toast.makeText(context, "未获取价格本信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnStartTime://获取起送时间
                getTimeDialog(v, 0);
                break;
            case R.id.btnEndTime://获取到达时间
                getTimeDialog(v, 1);
                break;
            case R.id.btnTransportEquip://获取运输设备
                name.clear();
                id.clear();
                if (globalDictionaryList != null) {
                    for (int i = 0; i < globalDictionaryList.size(); i++) {
                        name.add(globalDictionaryList.get(i).getValue());
                        id.add(globalDictionaryList.get(i).getKey());
                    }
                    show(btnTransportEquip, name, id);
                } else {
                    Toast.makeText(context, "未获取运输设备信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                }
                break;
            /*case R.id.btnDeliveryDept://获取运输单位
                name.clear();
                id.clear();
                if (deptList != null) {
                    for (int i = 0; i < deptList.size(); i++) {
                        name.add(deptList.get(i).getName());
                        id.add(deptList.get(i).getRefDeptId());
                    }
                    show(btnDeliveryDept, name, id);
                } else {
                    Toast.makeText(context, "未获取运输单位信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                }
                break;*/
            case R.id.btnDelAllVaccine://先将要展示的进行清除,展示  再将piatsInfoList里position相同的删除
                for (int i = piatsInfoList2.size() - 1; i > -1; i--) {
                    if (piatsInfoList2.get(i).getPosition() == application.getPosition()) {
                        piatsInfoList.remove(piatsInfoList2.get(i));
                        piatsInfoList2.remove(i);
                        recyclerAdapter.notifyItemRemoved(i);
                        recyclerAdapter.notifyItemRangeChanged(i, piatsInfoList2.size() - i);
                    }
                }
                piatsInfoList3.clear();
                break;
            case R.id.btnSubmitVaccine://回到储位界面
                piatsInfoList3.clear();
                piatsInfoList2.clear();
                startActivity(new Intent(PurchaseActivity.this, PurchaseStorageActivity.class));
                break;
        }

    }

    public void getTimeDialog(View view, int i) {

        TimePickerView timePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String start = getTime(date);
                ((TextView) view).setText(start);
                ((TextView) view).setTextColor(getResources().getColor(R.color.billTextChoose));
                if (i == 0) {
                    application.setRunTime(start);
                } else if (i == 1) {
                    application.setArrivalTime(start);
                }

            }
        }).setType(new boolean[]{true, true, true, true, true, true})
                .setCancelColor(getResources().getColor(R.color.colorCyan300))
                .setSubmitColor(getResources().getColor(R.color.colorCyan500)).build();
        //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        timePickerView.setDate(Calendar.getInstance());
        timePickerView.show();
    }


    /**
     * 比较出发和到达时间大小
     */
    public boolean compareDate(String start, String arrival) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = df.parse(start);
            Date arrivalDate = df.parse(arrival);
            if (startDate.before(arrivalDate)) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }


    public void getBack(Context context) {//
        broadcast = new MyBroadcastReceiver();
        IntentFilter mFilter = new IntentFilter("com.jhd.test.broadcast");
        context.registerReceiver(broadcast, mFilter);
    }

    public void getBackClose(Context context) {//
        if (broadcast != null) {
            context.unregisterReceiver(broadcast);
        }
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getStringExtra("type").equals("0")) {
                if (vp.getCurrentItem() == 1) {
                    vp.setCurrentItem(0);
                }
            } else if (intent.getStringExtra("type").equals("1")) {
                finish();
            } else if (intent.getStringExtra("type").equals("2")) {
                recyclerAdapter = new RecyclerAdapter(piatsInfoList);
                rvStorage.setAdapter(recyclerAdapter);
            }
        }
    }

    class BarcodeDataReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
            final String scanStatus = intent.getStringExtra("SCAN_STATE");
            if ("ok".equals(scanStatus)) {
                Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
                context.sendBroadcast(stopIntent);
                getVaccineInfoByCodeSingle(scanResult_1, context);
            }
        }
    }

    public void openScan(Context context) {
        barcodeDataReceiver = new BarcodeDataReceiver();
        IntentFilter mFilter = new IntentFilter("nlscan.action.SCANNER_RESULT");
        context.registerReceiver(barcodeDataReceiver, mFilter);
        Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
        mIntent.putExtra("SCAN_INTERVAL", Long.valueOf(3000));
        mIntent.putExtra("EXTRA_TRIG_MODE", 0);// 0 配置扫描头为普通触发模式 /1 配置扫描头为连续扫描模式 /2 配置扫描头为超时扫描模式*
        mIntent.putExtra("EXTRA_SCAN_MODE", 3);// 1 ：直接填充模式* /2 ：虚拟按键模式 /3 ：广播输出模式
        context.sendBroadcast(mIntent);
        Intent mIntent2 = new Intent("ACTION_BAR_SCANCFG");
        mIntent2.putExtra("EXTRA_SCAN_NOTY_SND", 1);
        mIntent2.putExtra("EXTRA_SCAN_NOTY_VIB", 1);
        sendBroadcast(mIntent2);
    }

    public void closeScan(Context context) {
        context.unregisterReceiver(barcodeDataReceiver);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ScanUtil.powerOffScan(context);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(vp.getCurrentItem()==1){
            ScanUtil.powerOnScan(context);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        piatsInfoList2.clear();
        piatsInfoList3.clear();
        if (piatsInfoList.size() > 0) {
            for (int i = 0; i < piatsInfoList.size(); i++) {
                if (piatsInfoList.get(i).getPosition() == application.getPosition()) {
                    piatsInfoList2.add(piatsInfoList.get(i));
                }
            }
            recyclerAdapter = new RecyclerAdapter(piatsInfoList2);
            rvStorage.setAdapter(recyclerAdapter);
        }
    }

    /*根据扫描code和orderType获取疫苗信息*/
    private void getVaccineInfoByCodeSingle(String code, Context context) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("code", code);
        params.put("orderType", "1");//自制单据
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getVaccineInfoByCodeSingle(token, params);
        jsonForResultCall.enqueue(new getVaccineInfoByCodeSingleCallback(code, context));
    }

    private class getVaccineInfoByCodeSingleCallback implements Callback<JsonForResult> {
        private String code;
        private Context context;

        public getVaccineInfoByCodeSingleCallback(String code, Context context) {
            this.code = code;
            this.context = context;
        }

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    if (jsonForResult.getData() == null) {
                        UtilHelper.alertMsg(PurchaseActivity.this, "错误", jsonForResult.getMessage());
                        return;
                    }
                    //请求授权信息
                    List<PiatsInfo> piatsInfo2 = JSON.parseArray(jsonForResult.getData().toString(), PiatsInfo.class);
                    if (CollectionUtil.isNullOrEmpty(piatsInfo2)) {
                        UtilHelper.alertMsg(PurchaseActivity.this, "错误", "获取疫苗信息失败!");
                        return;
                    }
                    PiatsInfo piatsInfo = piatsInfo2.get(0);
                    if(!application.getVaccineType().equals(piatsInfo.getCategory())){
                        UtilHelper.alertMsg(PurchaseActivity.this, "错误", "所扫疫苗的类型不符,请重新扫码!");
                        return;
                    }
                    if(isDeptCode){//deptCode为null,需要判断deptId是否一致
                        if(!produceMappingId.equals(piatsInfo.getProduceMappingId())){
                            UtilHelper.alertMsg(PurchaseActivity.this, "错误", "所扫疫苗的生产厂家与供货单位不一致,请重新扫码!");
                            return;
                        }
                    }
                    piatsInfo.setStorageName(application.getStorageName());
                    piatsInfo.setStorageId(application.getStorageId());
                    piatsInfo.setPosition(application.getPosition());
                    if (!isContain(piatsInfoList,piatsInfo)) {
                        piatsInfoList.add(piatsInfo);
                        piatsInfoList2.add(piatsInfo);
                        piatsInfoList3.add(piatsInfo);
                        if (piatsInfoList2.size() == 1) {
                            recyclerAdapter = new RecyclerAdapter(piatsInfoList2);
                            rvStorage.setAdapter(recyclerAdapter);
                        } else {
                            recyclerAdapter.notifyItemInserted(piatsInfoList2.size() - 1);
                            recyclerAdapter.notifyItemRangeChanged(piatsInfoList2.size() - 1, 1);//更新的位置,更新的总条数
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "该疫苗已经扫描", Toast.LENGTH_SHORT).show();
                    }
                } else if (jsonForResult != null && (!jsonForResult.isSuccess())) {
                    Toast.makeText(getApplicationContext(), jsonForResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(PurchaseActivity.this, "错误", msg);
        }
    }


    private boolean isContain(List<PiatsInfo> piatsInfoList,PiatsInfo piatsInfo){
        for (PiatsInfo info : piatsInfoList) {
            if(info.getCode().equals(piatsInfo.getCode())){
                return true;
            }
        }
        return false;
    }


    /*获取运输设备*/
    private void getGlobalDictionaryByType() {
        String baseUrl = UtilHelper.baseUrls.API(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("typeName", "冷链设备类型");
        String token = application.getAccessToken();
        VaccineService vs = retrofit.create(VaccineService.class);
        Call<JsonForResult> jsonForResultCall = vs.getGlobalDictionaryByType(token, params);
        jsonForResultCall.enqueue(new getGlobalDictionaryByTypeCallback());
    }

    private class getGlobalDictionaryByTypeCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    globalDictionaryList = JSON.parseArray(jsonForResult.getData().toString(), GlobalDictionary.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(PurchaseActivity.this, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取数据失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        }
    }


    private void show(TextView textView, List<String> name, List<String> id) {
        isCheck=false;
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new MyAdapter(textView,name, id));
        if(popup.isShowing())popup.dismiss();
        popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popup.setWidth(textView.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(textView, 0, 5);//显示在edit控件的下面0,0代表偏移量
        textView.setBackgroundResource(R.drawable.selector_focused);
        if(name.size()>0){
            popup.setOutsideTouchable(false);//点击PopupWindow以外的区域不关闭该窗口
        }
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                textView.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }

    //适配器
    private class MyAdapter extends BaseAdapter {
        private List<String> name, id;private TextView textView;

        public MyAdapter(TextView textView,List<String> name, List<String> id) {
            this.name = name;
            this.id = id;
            this.textView = textView;
        }

        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }

            holderView.text.setText(name.get(position));
            if (textView.getText().toString().equals(name.get(position))) {
                holderView.text.setTextColor(getResources().getColor(R.color.billChoosed));
            } else {
                holderView.text.setTextColor(getResources().getColor(R.color.billTextChoose));
            }
            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isCheck=true;
                    if (textView == btnApprovalIn) {//审批人
                        application.setApprovalId(id.get(position));
                    } else if (textView ==btnSupplyDept) {//供货单位
                        EditTextDel.setCanDel((LastInputEditText) textView,false);
                        application.setSupplyDeptId(id.get(position));
                        application.setSupplyDeptName(name.get(position));
                        produceMappingId=deptId.get(position);
                        if(deptCode.get(position)==null){
                            isDeptCode=true;
                        }
                    } else if (textView ==btnVaccineType) {//疫苗属性
                        application.setVaccineType(id.get(position));
                    } else if (textView ==btnPriceBook) {//价格本
                        application.setPriceNoIn(name.get(position));
                        application.setPriceBookMstId(id.get(position));
                    } else if (textView ==btnTransportEquip) {//运输设备
                        application.setColdChainType(id.get(position));
                    } else if (textView ==btnDeliveryDept) {//配送单位
                        EditTextDel.setCanDel((LastInputEditText) textView,false);
                        application.setTransformId(id.get(position));
                        application.setTransformName(name.get(position));
                    }
                    textView.setText(name.get(position));
                    textView.setTextColor(getResources().getColor(R.color.billTextChoose));
                    notifyDataSetChanged();
                    textView.setBackgroundResource(R.drawable.selector_unfocused);
                    popup.dismiss();
                }
            });
            return convertView;
        }
    }

    public class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
        private TextView text;
    }

    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
        private List<PiatsInfo> piatsInfos;

        public RecyclerAdapter(List<PiatsInfo> piatsInfos) {
            this.piatsInfos = piatsInfos;
        }

        @NonNull
        @Override
        public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaccine_attribute, parent, false);
            RecyclerAdapter.ViewHolder viewHolder = new RecyclerAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            holder.tv_electCode.setText(piatsInfos.get(position).getCode());
            holder.tvVaccineName.setText("疫苗名称:" + piatsInfos.get(position).getPhysicName());
            holder.tvFactory.setText(piatsInfos.get(position).getProduceName());
            holder.tvApprovalNo.setText(piatsInfos.get(position).getApproveNo());
            holder.tvVaccineDose.setText(piatsInfos.get(position).getPrepnSpec() + "/" + piatsInfos.get(position).getPkgSpec());
            holder.tvCodeLevelStr.setText(piatsInfos.get(position).getCodeLevelStr());
            holder.tvExpireDate.setText(piatsInfos.get(position).getExpireDate());
            holder.tvUnitPrice.setText(String.valueOf(piatsInfos.get(position).getUnitPrice()));
            holder.tvQuantity.setText(String.valueOf(piatsInfos.get(position).getPkgAmount()));
            holder.tvServicePrice.setText(String.valueOf(Integer.valueOf(piatsInfos.get(position).getPkgAmount()) * piatsInfos.get(position).getUnitPrice()));
            holder.tvStorage.setText(piatsInfos.get(position).getStorageName());
            if (piatsInfos.get(position).getCategory().equals("1")) {
                holder.iv_category.setText("免规");
            }else if(piatsInfos.get(position).getCategory().equals("4")){
                holder.iv_category.setText("地方免规");
            }else if(piatsInfos.get(position).getCategory().equals("5")){
                holder.iv_category.setText("应急");
            }else if(piatsInfos.get(position).getCategory().equals("2")){
                holder.iv_category.setText("非免规");
            }else if(piatsInfos.get(position).getCategory().equals("6")){
                holder.iv_category.setText("群体性预防");
            }else if(piatsInfos.get(position).getCategory().equals("7")){
                holder.iv_category.setText("紧急");
            }
            holder.iv_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < piatsInfoList.size(); i++) {
                        if (piatsInfoList.get(i).getCode().equals(piatsInfos.get(position).getCode())) {
                            piatsInfoList.remove(i);
                        }
                    }
                    for (int i = 0; i < piatsInfoList3.size(); i++) {
                        if (piatsInfoList3.get(i).getCode().equals(piatsInfos.get(position).getCode())) {
                            piatsInfoList3.remove(i);
                        }
                    }
                    piatsInfoList2.remove(position);
                    notifyItemRemoved(position);//移除该位置的项目
                    notifyItemRangeChanged(position, getItemCount() - position);//局部刷新从该position位置开始到剩余的所有项目
                }
            });
        }

        @Override
        public int getItemCount() {
            return piatsInfos.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_electCode, tvVaccineName, tvFactory, tvApprovalNo,iv_category; //追溯码,疫苗名称，生产厂家，批号,疫苗属性
            TextView tvVaccineDose, tvCodeLevelStr, tvExpireDate, tvUnitPrice, tvQuantity, tvServicePrice, tvStorage; // 计量规格,包装类型,效期,单价,数量,金额,储位
            ImageView iv_del;
            LinearLayout linStorage;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_electCode = itemView.findViewById(R.id.tv_electCode);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.iv_del = itemView.findViewById(R.id.iv_del);
                this.iv_category = itemView.findViewById(R.id.iv_category);
                this.tvFactory = itemView.findViewById(R.id.tvFactory);
                this.tvApprovalNo = itemView.findViewById(R.id.tvApprovalNo);
                this.tvVaccineDose = itemView.findViewById(R.id.tvVaccineDose);
                this.tvCodeLevelStr = itemView.findViewById(R.id.tvCodeLevelStr);
                this.tvExpireDate = itemView.findViewById(R.id.tvExpireDate);
                this.tvUnitPrice = itemView.findViewById(R.id.tvUnitPrice);
                this.tvQuantity = itemView.findViewById(R.id.tvQuantity);
                this.tvServicePrice = itemView.findViewById(R.id.tvServicePrice);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.linStorage = itemView.findViewById(R.id.linStorage);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeScan(context);
        piatsInfoList.clear();
        piatsInfoList2.clear();
        getBackClose(this);
        application.clearBill();//将bill里的数据清除
    }
}